package com.huawei.cloudapp.ui.fragment.home;

import static android.content.Context.MODE_PRIVATE;
import static android.view.View.GONE;
import static android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE;
import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_DRAGGING;
import static com.huawei.cloudapp.utils.CasConstantsUtil.COMMON;
import static com.huawei.cloudapp.utils.CasConstantsUtil.EMPTY_STRING;
import static com.huawei.cloudapp.utils.CasConstantsUtil.IAM_USERNAME;
import static com.huawei.cloudapp.utils.CasConstantsUtil.PHONE_ID;
import static com.huawei.cloudapp.utils.CasConstantsUtil.PHONE_NAME;
import static com.huawei.cloudapp.utils.CasConstantsUtil.PHONE_STATUS;
import static com.huawei.cloudapp.utils.CasConstantsUtil.PROJECT_ID;
import static com.huawei.cloudapp.utils.CasConstantsUtil.REGION_ID;
import static com.huawei.cloudapp.utils.CasConstantsUtil.REGION_INFO;
import static com.huawei.cloudapp.utils.CasConstantsUtil.REGION_NAME;
import static com.huawei.cloudapp.utils.CasConstantsUtil.SELECTED_REGION_POSITION;
import static com.huawei.cloudapp.utils.CasConstantsUtil.SERVER_ID;
import static com.huawei.cloudapp.utils.CasConstantsUtil.SESSION_ID;
import static com.huawei.cloudapp.utils.CasConstantsUtil.TOKEN;
import static com.huawei.cloudapp.utils.CasConstantsUtil.TOKEN_EXPIRE_TIME;
import static com.huawei.cloudapp.utils.CasConstantsUtil.USERNAME;
import static com.huawei.cloudapp.utils.CasConstantsUtil.USER_INFO;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.SearchView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.google.android.material.appbar.AppBarLayout;
import com.hjq.toast.ToastParams;
import com.hjq.toast.Toaster;
import com.hjq.toast.style.CustomToastStyle;
import com.huawei.cloudapp.R;
import com.huawei.cloudapp.common.CasCommonDialog;
import com.huawei.cloudapp.common.CasRecord;
import com.huawei.cloudapp.model.IHandleData;
import com.huawei.cloudapp.model.IUserModel;
import com.huawei.cloudapp.model.bean.CustomException;
import com.huawei.cloudapp.model.bean.Phone;
import com.huawei.cloudapp.model.bean.PhoneInfo;
import com.huawei.cloudapp.model.bean.User;
import com.huawei.cloudapp.model.bean.direct.PhoneDetail;
import com.huawei.cloudapp.model.bean.direct.PhoneJobResponse;
import com.huawei.cloudapp.model.direct.PhoneModel;
import com.huawei.cloudapp.presenter.PhonePresenter;
import com.huawei.cloudapp.presenter.UserPresenter;
import com.huawei.cloudapp.ui.activity.CasCloudLoginActivity;
import com.huawei.cloudapp.ui.activity.CasCloudPhoneActivity;
import com.huawei.cloudapp.ui.adapter.PhoneListAdapter;
import com.huawei.cloudapp.ui.fragment.CloudPhoneFragment;
import com.huawei.cloudapp.ui.views.CasArcView;
import com.huawei.cloudapp.utils.CasAESKeystoreUtils;
import com.huawei.cloudapp.utils.CasCommonUtils;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class PhoneListFragment extends CloudPhoneFragment implements IHandleData<Object>, OnRefreshListener, OnLoadMoreListener {
    
    private static final String TAG = "PhoneListFragment";
    private static final int LIMIT = 30;

    private Activity mActivity;
    private AppCompatSpinner regionSpinner;
    private AppCompatSpinner searchSpinner;
    private ArrayAdapter<String> regionSpinnerAdapter;
    private ArrayAdapter<String> searchTypeSpinnerAdapter;
    private SearchView mSearchView;
    private CasRecord mCommonCasRecord;
    private CasRecord mUserCasRecord;
    private boolean isLogin;
    private String selectedRegion;
    private int selectedQueryType;
    private String queryContent = EMPTY_STRING;
    private User mUser;
    private CasCommonDialog mDialog;
    private int offset = 0;
    private RecyclerView mRecyclerView;
    private int mPosition = 0;
    private SmartRefreshLayout mRefreshLayout;
    private int mViewType = 1;
    private ImageView mViewTypeIV;

    private PhoneListAdapter mPhoneListAdapter;
    private LinearLayoutManager mLayoutManager;
    private LinearLayout mLayout;
    private LinearLayout mSearchViewLayout;
    private LinearLayout mSearchPopupLayout;
    private PopupWindow mStatusPopupWindow;
    private PopupWindow mSearchPopupWindow;
    private AppBarLayout mAppBar;
    private TextView mTVPopStatus;
    private TextView mTVSearchContent;
    private TextView mTVSearchContentClose;
    private ImageView mSwitchLayoutIV;
    private ImageView mToolbarSearchView;
    private CasArcView mArcView;
    private Button mEnterCloudPhoneButton;

    private List<PhoneJobResponse> jobList = new ArrayList<>();
    private boolean isReadyToExit = false;
    private boolean isReload = true;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        mUserCasRecord = new CasRecord(getActivity().getSharedPreferences(USER_INFO, MODE_PRIVATE));
        String username = mUserCasRecord.getRecord(USERNAME);
        if (username == null || username.isEmpty()) {
            finishAndReLogin(true);
        } else {
            mUser = new User(username,
                    mUserCasRecord.getRecord(IAM_USERNAME),
                    mUserCasRecord.getHashMapRecord(TOKEN),
                    mUserCasRecord.getHashMapRecord(TOKEN_EXPIRE_TIME),
                    mUserCasRecord.getHashMapRecord(PROJECT_ID),
                    EMPTY_STRING);
            isLogin = true;
        }
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mActivity = (Activity) context;
        Toaster.init(mActivity.getApplication());
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mLayout = view.findViewById(R.id.recycler_view_parent);
        mCommonCasRecord = new CasRecord(view.getContext().getSharedPreferences(COMMON, MODE_PRIVATE));
        mSwitchLayoutIV = view.findViewById(R.id.cas_view_type);
        mSwitchLayoutIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchLayout();
            }
        });

        mActivity.getWindow().setBackgroundDrawable(AppCompatResources.getDrawable(getContext(), R.drawable.main_background));
        mTVSearchContent = view.findViewById(R.id.tv_search_content);

        mTVSearchContentClose = view.findViewById(R.id.tv_search_content_close);
        mTVSearchContentClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTVSearchContent.setText("搜索");
                queryContent = EMPTY_STRING;
                mSearchView.setQuery(EMPTY_STRING, false);
                mTVSearchContentClose.setVisibility(GONE);
                getUserPhoneList(true);
            }
        });

        regionSpinner = view.findViewById(R.id.region_spinner);
        regionSpinnerAdapter = new ArrayAdapter<>(mActivity, R.layout.spinner_item, new ArrayList<>(REGION_INFO.values()));
        regionSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        regionSpinner.setAdapter(regionSpinnerAdapter);
        regionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (!isReload && selectedRegion != null && !selectedRegion.isEmpty() && selectedRegion.equals(REGION_NAME.get(i))){
                    return;
                }
                isReload = false;
                if (mCommonCasRecord != null) {
                    mCommonCasRecord.setRecord(SELECTED_REGION_POSITION, String.valueOf(i));
                    selectedRegion = REGION_NAME.get(i);
                }
                HashMap<String, String> tokens = mUserCasRecord.getHashMapRecord(TOKEN);
                if(!tokens.containsKey(selectedRegion)) {
                    getUserInfo();
                } else {
                    getUserPhoneList(true);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

        String selectedRegionPosition = mCommonCasRecord.getRecord(SELECTED_REGION_POSITION);
        if (selectedRegionPosition == null || selectedRegionPosition.isEmpty()) {
            regionSpinner.setSelection(6);
        } else {
            regionSpinner.setSelection(Integer.parseInt(selectedRegionPosition));
        }

        mViewTypeIV = view.findViewById(R.id.cas_view_type);
        mViewTypeIV.setImageResource(R.drawable.cas_view_carousel);

        mStatusPopupWindow = new PopupWindow(view.getContext());
        mStatusPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        mStatusPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mStatusPopupWindow.setOutsideTouchable(true);
        mStatusPopupWindow.setElevation(100f);
        mStatusPopupWindow.setFocusable(true);
        mStatusPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mTVPopStatus = (TextView) View.inflate(view.getContext(), R.layout.cas_pop_up_window_status, null);

        mSearchPopupWindow = new PopupWindow(view.getContext());
        mSearchPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        mSearchPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mSearchPopupWindow.setOutsideTouchable(true);
        mSearchPopupWindow.setElevation(100f);
        mSearchPopupWindow.setFocusable(true);
        mSearchPopupLayout = (LinearLayout) View.inflate(view.getContext(), R.layout.cas_search_view, null);
        mSearchPopupWindow.setContentView(mSearchPopupLayout);

        mToolbarSearchView = view.findViewById(R.id.toolbar_search_view);
        mAppBar = view.findViewById(R.id.main_appbar);
        mAppBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (Math.abs(verticalOffset) == mAppBar.getTotalScrollRange()) {
                    mToolbarSearchView.setVisibility(View.VISIBLE);
                } else if (verticalOffset == 0) {
                    mToolbarSearchView.setVisibility(GONE);
                }
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mAppBar.setOutlineProvider(null);
            mToolbarSearchView.setOutlineProvider(ViewOutlineProvider.BOUNDS);
        }

        mRefreshLayout = view.findViewById(R.id.refresh_layout);
        mRefreshLayout.setEnableLoadMore(true).setOnRefreshListener(this).setOnLoadMoreListener(this).setEnableAutoLoadMore(true);
        mArcView = view.findViewById(R.id.arcView);
        mEnterCloudPhoneButton = view.findViewById(R.id.app_connect);

        mSearchViewLayout = view.findViewById(R.id.search_layout);
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showSearchView(mSearchPopupLayout);
            }
        };
        mSearchViewLayout.setOnClickListener(listener);
        mToolbarSearchView.setOnClickListener(listener);

        if (!isReload && mPhoneListAdapter != null) {
            offset = 0;
            showPhoneList(mPhoneListAdapter.getData(), true, true);
        }
    }

    // UI
    private void prepareRecyclerView() {
        mLayout.removeView(mRecyclerView);
        mRecyclerView = new RecyclerView(getContext());
        mRecyclerView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mRecyclerView.setClipToPadding(false);
        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(mRecyclerView);

        if (mViewType == 0) {
            mLayoutManager = new LinearLayoutManager(getContext());
            mPhoneListAdapter = new PhoneListAdapter(R.layout.cas_phone_item_list);
            mRecyclerView.clearOnScrollListeners();
            mRecyclerView.setPadding(0, 0, 0, 0);
            mArcView.setVisibility(GONE);
            mEnterCloudPhoneButton.setVisibility(GONE);
        } else {
            mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
            mPhoneListAdapter = new PhoneListAdapter(R.layout.cas_phone_item_card);
            mRecyclerView.setPadding(CasCommonUtils.dip2px(getContext(), 30), 0, CasCommonUtils.dip2px(getContext(), 30), 0);
            mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    int childCount = recyclerView.getChildCount();
                    for (int i = 0; i < childCount; i++) {
                        View child = recyclerView.getChildAt(i);
                        int left = child.getLeft();
                        int paddingStart = recyclerView.getPaddingStart();
                        // 遍历recyclerView子项，以中间项左侧偏移量为基准进行缩放
                        float bl = Math.min(1, Math.abs(left - paddingStart) * 1f / child.getWidth());
                        float scale = (float) (1 - bl * (1 - 0.9));
                        child.setScaleY(scale);
                    }
                }

                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    if (newState == SCROLL_STATE_IDLE || newState == SCROLL_STATE_DRAGGING) {
                        RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager();
                        if (layoutManager instanceof LinearLayoutManager) {
                            LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
                            int firstVisiblePosition = linearLayoutManager.findFirstVisibleItemPosition();
                            int lastVisiblePosition = linearLayoutManager.findLastVisibleItemPosition();
                            if (firstVisiblePosition == recyclerView.getChildCount() - 1 &&
                                    lastVisiblePosition == recyclerView.getChildCount()) {
                                mPosition = lastVisiblePosition;
                            } else {
                                mPosition = (firstVisiblePosition + lastVisiblePosition) / 2;
                            }
                        }
                    }
                }
            });
        }
        mPhoneListAdapter.addChildClickViewIds(R.id.tv_item_reset, R.id.tv_item_restart,
                R.id.iv_phone_status, R.id.tv_server_detail, R.id.layout_item,
                R.id.tv_phone_name, R.id.tv_phone_id, R.id.tv_phone_model, R.id.tv_image_id, R.id.server_item_layout);
        mPhoneListAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (mViewType != 0 && position != mPosition) {
                    Log.e(TAG, "Click another view, ignore.");
                    return;
                }
                Phone phone = mPhoneListAdapter.getItem(position).getPhone();
                if (view.getId() == R.id.tv_item_reset) {
                    showPhoneActionDialog(false, phone.getPhoneName(),
                            getResources().getString(R.string.reset_the_phone),
                            phone.getPhoneId());
                } else if (view.getId() == R.id.tv_item_restart) {
                    showPhoneActionDialog(true, phone.getPhoneName(),
                            getResources().getString(R.string.restart_the_phone),
                            phone.getPhoneId());
                } else if (view.getId() == R.id.iv_phone_status) {
                    mTVPopStatus.setText(PHONE_STATUS.get(phone.getStatus()));
                    mStatusPopupWindow.setContentView(mTVPopStatus);
                    mStatusPopupWindow.showAsDropDown(view);
                } else if (view.getId() == R.id.tv_server_detail) {
                    getPhoneDetail(phone.getPhoneId());
                } else if (view.getId() == R.id.tv_phone_name || view.getId() == R.id.tv_phone_id || view.getId() == R.id.tv_phone_model || view.getId() == R.id.tv_image_id) {
                } else {
                    startCloudPhoneActivity(mPhoneListAdapter.getItem(position));
                }
            }
        });
        mRecyclerView.setAdapter(mPhoneListAdapter);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mLayout.addView(mRecyclerView);

        if (mViewType == 0) {
            mArcView.setVisibility(GONE);
            mEnterCloudPhoneButton.setVisibility(GONE);
        } else {
            DisplayMetrics metrics = new DisplayMetrics();
            mActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
            int physicalWidth = metrics.widthPixels;
            int physicalHeight = metrics.heightPixels;
            ViewGroup.LayoutParams layoutParams = mArcView.getLayoutParams();
            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            layoutParams.height = physicalHeight / 6;
            mArcView.setLayoutParams(layoutParams);
            mArcView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                }
            });
            mArcView.bringToFront();

            CoordinatorLayout.LayoutParams buttonLayoutParams = (CoordinatorLayout.LayoutParams) mEnterCloudPhoneButton.getLayoutParams();
            buttonLayoutParams.setMargins(0, 0, 0, physicalHeight / 15);
            buttonLayoutParams.height = physicalHeight / 16;
            buttonLayoutParams.width = physicalWidth / 3;
            mEnterCloudPhoneButton.setLayoutParams(buttonLayoutParams);
            mEnterCloudPhoneButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mPhoneListAdapter.getData().isEmpty()) {
                        return;
                    }
                    startCloudPhoneActivity(mPhoneListAdapter.getItem(mPosition));
                }
            });
            mEnterCloudPhoneButton.bringToFront();

            mArcView.setVisibility(View.VISIBLE);
            mEnterCloudPhoneButton.setVisibility(View.VISIBLE);
        }

        offset = 0;
    }

    private void showPhoneList(List<PhoneInfo> phoneInfoList, boolean isRefreshData, boolean isRefreshView) {
        if (mLayoutManager == null || mPhoneListAdapter == null || isRefreshView) {
            prepareRecyclerView();
        }

        if (isRefreshData) {
            mPhoneListAdapter.setNewInstance(phoneInfoList);
        } else {
            mPhoneListAdapter.addData(phoneInfoList);
        }

        offset += phoneInfoList.size();
    }

    public void switchLayout() {
        if (mPhoneListAdapter == null) return;
        mViewType ++;
        mViewType = mViewType % 2;
        List<PhoneInfo> phoneInfoList = mPhoneListAdapter.getData();
        if (mViewType == 0) {
            mViewTypeIV.setImageResource(R.drawable.cas_view_list);
        } else {
            mAppBar.setExpanded(true,true);
            mViewTypeIV.setImageResource(R.drawable.cas_view_carousel);
        }
        showPhoneList(phoneInfoList, true, true);
    }

    public void showPhoneActionDialog(boolean isRestart, String phoneName, String message, String phoneId) {
        if (mDialog == null || !mDialog.isShowing()) {
            final View contentView = View.inflate(getActivity(), R.layout.cas_set_ui_level, null);
            final CasCommonDialog.Builder builder = new CasCommonDialog.Builder(getActivity());
            CasCommonDialog.DialogClickListener dialogListener = new CasCommonDialog.DialogClickListener();

            builder.setTitle(phoneName);
            builder.setMessage(message);
            builder.setContentView(contentView);
            builder.setPositiveButton(getResources().getString(R.string.cas_phone_cancel_tip_message), dialogListener);
            builder.setNegativeButton(getResources().getString(R.string.cas_phone_confirm_tip_message), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (isRestart) {
                        restartPhone(phoneId);
                    } else {
                        resetPhone(phoneId);
                    }
                }
            });

            mDialog = builder.create();
            mDialog.setCancelable(true);
            if (!getActivity().isFinishing()) {
                mDialog.show();
            }
        }
    }

    private PhoneInfo phoneDetailToPhoneInfo(PhoneDetail phoneDetail) {
        Phone phone = new Phone();
        phone.setPhoneId(phoneDetail.getPhoneId());
        phone.setPhoneName(phoneDetail.getPhoneName());
        phone.setAvailabilityZone(phoneDetail.getAvailabilityZone());
        phone.setCreateTime(phoneDetail.getCreateTime());
        phone.setUpdateTime(phoneDetail.getUpdateTime());
        phone.setPhoneModelName(phoneDetail.getPhoneModelName());
        phone.setImageId(phoneDetail.getImageId());
        phone.setImageVersion(phoneDetail.getImageVersion());
        phone.setImei(String.valueOf(phoneDetail.getImei()));
        phone.setMetadata(phoneDetail.getMetadata());
        phone.setServerId(phoneDetail.getServerId());
        phone.setStatus(phoneDetail.getStatus());
        phone.setTrafficType(phoneDetail.getTrafficType());
        phone.setVncEnable("false");
        phone.setVolumeMode(phoneDetail.getVolumeMode());
        return new PhoneInfo(phone, EMPTY_STRING, selectedRegion);
    }

    private void showPhoneDetail(PhoneDetail phoneDetail) {

    }

    private void showSearchView(View view) {
        CustomDialog.build()
                .setCustomView(new OnBindView<CustomDialog>(R.layout.cas_search_view) {
                    @Override
                    public void onBind(final CustomDialog dialog, View v) {
                        mSearchView = v.findViewById(R.id.search_view_popup_window);
                        
                        //设置搜索下拉框
                        searchSpinner = v.findViewById(R.id.search_spinner);
                        List<String> searchTypeList = Arrays.asList("名称", "服务器id", "云手机id");
                        searchTypeSpinnerAdapter = new ArrayAdapter<>(mActivity, R.layout.spinner_item_search, searchTypeList);
                        searchTypeSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        searchSpinner.setAdapter(searchTypeSpinnerAdapter);
                        //设置搜索下拉框的监听器
                        searchSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                selectedQueryType = i;
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {
                            }
                        });
                        searchSpinner.setSelection(selectedQueryType);
                        mSearchView.setQuery(queryContent, false);
                        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                            @Override
                            public boolean onQueryTextSubmit(String s) {
                                if (CasCommonUtils.isFastClick()) {
                                    return false;
                                }
                                queryContent = s;
                                boolean isQueryContentValid = true;
                                if (selectedQueryType == 1 || selectedQueryType == 2) {
                                    if (!CasCommonUtils.isValidUUID(queryContent)) {
                                        isQueryContentValid = false;
                                    }
                                } else {
                                    if (!CasCommonUtils.isValidPhoneName(queryContent)) {
                                        isQueryContentValid = false;
                                    }
                                }

                                if (!isQueryContentValid) {
                                    ToastParams params = new ToastParams();
                                    params.text = getResources().getString(R.string.query_intent_invalid);
                                    params.style = new CustomToastStyle(R.layout.toast_error);
                                    Toaster.show(params);
                                    return false;
                                }

                                if (!queryContent.equals(EMPTY_STRING) && selectedQueryType == 2) {
                                    getPhoneDetail(queryContent);
                                } else {
                                    getUserPhoneList(true);
                                }

                                List<String> searchTypeList = Arrays.asList(new String[]{"名称", "服务器id", "云手机id", "状态"});
                                mTVSearchContent.setText(searchTypeList.get(selectedQueryType) + ":" + queryContent);
                                mTVSearchContentClose.setVisibility(View.VISIBLE);
                                mSearchView.setQuery(queryContent, false);
                                mAppBar.setExpanded(true,true);
                                dialog.dismiss();
                                return true;
                            }

                            @Override
                            public boolean onQueryTextChange(String s) {
                                return false;
                            }

                        });
                    }
                })
                .setAlign(CustomDialog.ALIGN.TOP_CENTER).setMaskColor(getResources().getColor(R.color.black60))
                .show();

    }

    // 请求
    private void getUserInfo() {
        String username = mUserCasRecord.getRecord(USERNAME);
        if (username == null || username.isEmpty()) {
            finishAndReLogin(true);
            return;
        }
        String pass = CasCommonUtils.getEncryptPass();
        if (pass == null || pass.isEmpty()) {
            finishAndReLogin(true);
            return;
        }
        String iv = CasCommonUtils.getEncryptIV();
        if (iv == null || iv.isEmpty()) {
            finishAndReLogin(true);
            return;
        }
        String decryptPass = CasAESKeystoreUtils.decryptData(pass, iv);

        if (mUser == null) {
            mUser = new User(username,
                    mUserCasRecord.getRecord(IAM_USERNAME),
                    mUserCasRecord.getHashMapRecord(TOKEN),
                    mUserCasRecord.getHashMapRecord(TOKEN_EXPIRE_TIME),
                    mUserCasRecord.getHashMapRecord(PROJECT_ID),
                    EMPTY_STRING);
        }
        IUserModel userModel = new com.huawei.cloudapp.model.direct.UserModel();
        UserPresenter userPresenter = new UserPresenter(this, userModel);
        userPresenter.getUser(mUser, decryptPass, selectedRegion);
    }

    private void getUserPhoneList(boolean isClearData) {
        if (isClearData) {
            offset = 0;
            if (mPhoneListAdapter != null && !mPhoneListAdapter.getData().isEmpty()) {
                mPhoneListAdapter.setNewInstance(null);
            }
            mPosition = 0;
        }
        PhoneModel phoneModel  = new PhoneModel();
        PhonePresenter phonePresenter = new PhonePresenter(this, phoneModel);
        HashMap<String, String> condition = new HashMap<>();

        if (queryContent != null && !queryContent.isEmpty()) {
            if (selectedQueryType == 0) {
                condition.put(PHONE_NAME, queryContent);
            } else if (selectedQueryType == 1) {
                condition.put(SERVER_ID, queryContent);
            }
        }

        phonePresenter.getPhoneList(mUser, condition, selectedRegion, mUser.getUserProjectId().get(selectedRegion), offset, LIMIT);
    }

    private void getPhoneDetail(String phoneId) {
        PhoneModel phoneModel  = new PhoneModel();
        PhonePresenter phonePresenter = new PhonePresenter(this, phoneModel);
        phonePresenter.getPhoneDetailInfo(mUser, selectedRegion, mUser.getUserProjectId().get(selectedRegion), phoneId);
        mPosition = 0;
    }

    private void restartPhone(String phoneId) {
        PhoneModel phoneModel  = new PhoneModel();
        PhonePresenter phonePresenter = new PhonePresenter(this, phoneModel);
        phonePresenter.restartPhone(mUser, selectedRegion,
                mUser.getUserProjectId().get(selectedRegion),
                EMPTY_STRING, null, Collections.singletonList(phoneId));
        mDialog.dismiss();
    }

    private void resetPhone(String phoneId) {
        PhoneModel phoneModel  = new PhoneModel();
        PhonePresenter phonePresenter = new PhonePresenter(this, phoneModel);
        phonePresenter.resetPhone(mUser, selectedRegion,
                mUser.getUserProjectId().get(selectedRegion),
                EMPTY_STRING, null, Collections.singletonList(phoneId));
        mDialog.dismiss();
    }

    // 连接
    private void startCloudPhoneActivity(PhoneInfo phoneInfo) {
        if (CasCommonUtils.isFastClick() || !isLogin) {
            return;
        }

        Intent intent = new Intent(getActivity(), CasCloudPhoneActivity.class);
        if (phoneInfo.getPhoneId().isEmpty()) {
            return;
        }
        intent.putExtra(PHONE_ID, phoneInfo.getPhoneId());
        intent.putExtra(User.BUNDLE_KEY, mUser);
        intent.putExtra(REGION_ID, selectedRegion);
        startActivity(intent);
        getActivity().overridePendingTransition(0, 0);
    }

    private void finishAndReLogin(boolean isPrompt) {
        if (isPrompt) {
            //提示客户需要重新登陆
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastParams params = new ToastParams();
                    params.text = getResources().getString(R.string.user_info_invalid_need_login);
                    params.style = new CustomToastStyle(R.layout.toast_error);
                    Toaster.show(params);
                }
            });
        }
        getActivity().getSharedPreferences(USER_INFO, MODE_PRIVATE).edit().clear().apply();
        Intent intent = new Intent(getActivity(), CasCloudLoginActivity.class);
        startActivity(intent);
        getActivity().finish();
    }

    @Override
    public boolean onBackPressed() {
        if (mDialog != null &&  mDialog.isShowing()) {
            mDialog.dismiss();
            return true;
        }
        if (!isReadyToExit) {
            Toaster.show(R.string.cas_exit_app_confirmation);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    isReadyToExit = false;
                }
            }, 2000);
            isReadyToExit = true;
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onResume() {
        Log.e(TAG, "onResume: ");
        super.onResume();
    }

    @Override
    public void handleData(List<Object> list, int count) {
        if (count == 0) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //提示为空
                    showPhoneList(new ArrayList<>(),true, false);
                }
            });
        } else if (list.size() == 0) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //提示为空
                    ToastParams params = new ToastParams();
                    params.text = getResources().getString(R.string.no_more_response);
                    params.style = new CustomToastStyle(R.layout.toast_info);
                    Toaster.show(params);
                    if (mRefreshLayout != null) {
                        mRefreshLayout.finishRefresh(true).finishLoadMore(true);
                    }
                }
            });
        } else if (((List<?>) list).get(0) instanceof User) {
            List<User> users = (List<User>) (List<?>) list;
            User user = users.get(0);
            mUserCasRecord.setRecord(USERNAME, user.getUsername());
            mUserCasRecord.setRecord(IAM_USERNAME, user.getIamUsername());
            HashMap<String, String> tokens = user.getUserToken();
            mUserCasRecord.setHashMapRecord(TOKEN, tokens);
            HashMap<String, String> tokenExpireTimes = user.getUserTokenExpireTime();
            mUserCasRecord.setHashMapRecord(TOKEN_EXPIRE_TIME, tokenExpireTimes);
            HashMap<String, String> projectIds = user.getUserProjectId();
            mUserCasRecord.setHashMapRecord(PROJECT_ID, projectIds);
            mUserCasRecord.setRecord(SESSION_ID, user.getUserSessionId());
            mUser = user;
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    getUserPhoneList(true);
                }
            });
        } else if (((List<?>) list).get(0) instanceof PhoneInfo) {
            List<PhoneInfo> phones = (List<PhoneInfo>) (List<?>) list;
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    boolean isRefreshData;
                    if (mPhoneListAdapter != null) {
                        isRefreshData = mPhoneListAdapter.getData().size() == 0;
                    } else {
                        isRefreshData = true;
                    }
                    showPhoneList(phones, isRefreshData, false);
                    if (mRefreshLayout != null) {
                        mRefreshLayout.finishRefresh(true).finishLoadMore(true);
                    }
                }
            });
        } else if (((List<?>) list).get(0) instanceof PhoneDetail) {
            List<PhoneDetail> phoneDetail = (List<PhoneDetail>) (List<?>) list;
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (selectedQueryType == 2) {
                        showPhoneList(
                                Collections.singletonList(phoneDetailToPhoneInfo(phoneDetail.get(0))),
                                true, false);
                    } else {
                        showPhoneDetail(phoneDetail.get(0));
                    }
                    if (mRefreshLayout != null) {
                        mRefreshLayout.finishRefresh(true).finishLoadMore(true);
                    }
                }
            });
        } else if (((List<?>) list).get(0) instanceof PhoneJobResponse) {
            List<PhoneJobResponse> phoneJobs = (List<PhoneJobResponse>) (List<?>) list;
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    jobList.addAll(phoneJobs);
                    ToastParams params = new ToastParams();
                    params.text = getResources().getString(R.string.job_has_been_delivered);
                    params.style = new CustomToastStyle(R.layout.toast_success);
                    Toaster.show(params);
                }
            });
        }
    }

    @Override
    public void handleError(Exception e) {
        Log.e(TAG, "handleError: " + e);
        if (e instanceof CustomException.TokenExpireException) {
            getUserInfo();
        } else if (e instanceof CustomException.LogInInfoErrorException
                || e instanceof CustomException.FailedToLogInException ) {
            finishAndReLogin(true);
        } else {
            String message;
            if (e instanceof CustomException.FailedToGetPhoneListException) {
                message = getResources().getString(R.string.failed_to_get_phone_list);
            } else if (e instanceof CustomException.EmptyResponseFromServerException) {
                message = getResources().getString(R.string.cas_phone_connect_server_fail_tip_message);
            } else if (e instanceof CustomException.NoPermissionException) {
                message = getResources().getString(R.string.no_permission);
            }else if (e instanceof CustomException.OpRestrictedException) {
                message = getResources().getString(R.string.op_restricted);
            } else if (e instanceof CustomException.OpSuspendedException) {
                message = getResources().getString(R.string.op_suspended);
            } else if (e instanceof CustomException.OpUnverifiedException) {
                message = getResources().getString(R.string.op_unverified);
            } else if (e instanceof CustomException.DeliverJobFailedException) {
                message = getResources().getString(R.string.job_deliver_failed);
            }  else if (e instanceof CustomException.ServerError) {
                message = getResources().getString(R.string.service_internal_error);
            } else if (e instanceof CustomException.ParamInvalidException ||
                    e instanceof CustomException.PhoneNotFoundException ||
                    e instanceof CustomException.JobNotFoundException ||
                    e instanceof CustomException.ServerNotFoundException ||
                    e instanceof CustomException.ResourceNotFoundException) {
                message = getResources().getString(R.string.param_invalid);
            } else {
                message = getResources().getString(R.string.request_failed);
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastParams params = new ToastParams();
                    params.text = message;
                    params.style = new CustomToastStyle(R.layout.toast_error);
                    Toaster.show(params);
                    if (mRefreshLayout != null) {
                        mRefreshLayout.finishRefresh(true).finishLoadMore(true);
                    }
                }
            });
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        if (mUser == null || selectedRegion == null || selectedRegion.isEmpty()
                || !mUser.getUserToken().containsKey(selectedRegion)
                || !mUser.getUserTokenExpireTime().containsKey(selectedRegion)
                || !mUser.getUserProjectId().containsKey(selectedRegion)) {
            return;
        }
        Log.e(TAG, "onLoadMore: offset = " + offset);
        if (!queryContent.equals(EMPTY_STRING) && selectedQueryType == 2) {
            getPhoneDetail(queryContent);
        } else {
            getUserPhoneList(false);
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        if (mUser == null || selectedRegion == null || selectedRegion.isEmpty()
                || !mUser.getUserToken().containsKey(selectedRegion)
                || !mUser.getUserTokenExpireTime().containsKey(selectedRegion)
                || !mUser.getUserProjectId().containsKey(selectedRegion)) {
            return;
        }
        if (mPhoneListAdapter != null && !mPhoneListAdapter.getData().isEmpty()) {
            mPhoneListAdapter.setNewInstance(new ArrayList<>());
        }
        if (!queryContent.equals(EMPTY_STRING) && selectedQueryType == 2) {
            getPhoneDetail(queryContent);
        } else {
            getUserPhoneList(true);
        }
    }
}
